package simple.utils.processing;

import java.util.concurrent.TimeUnit;

/**
 * Created with IntelliJ IDEA.
 * User: rehak
 * Date: 5/28/13
 * Time: 4:37 PM
 * To change this template use File | Settings | File Templates.
 */
public class Timer {

    private Long startedOn = null;
    private Long stoppedOn = null;

    private long nanos() {
        return System.nanoTime();
    }

    public long start() {
        startedOn = nanos();
        return startedOn;
    }

    public long stop() {
        if (startedOn == null) {
            throw new IllegalArgumentException("Not started yet!");
        }
        stoppedOn = nanos();
        return stoppedOn;
    }

    public void reset() {
        startedOn = null;
        stoppedOn = null;
    }

    public boolean isStarted() {
        return startedOn != null;
    }

    public boolean isFinished() {
        return stoppedOn != null;
    }

    public long getDuration(TimeUnit unit) {
        if (startedOn == null) {
            throw new IllegalArgumentException("Not started yet!");
        }
        long start = startedOn;
        long stop;
        if (isFinished()) {
            stop = stoppedOn;
        } else {
            stop = nanos();
        }
        long nanos = stop - start;
        long val = unit.convert(nanos, TimeUnit.NANOSECONDS);
        return val;
    }

}
